import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/common/xindong_storage.dart';
import 'package:xindong/manager/xindong_tencent_singleton.dart';
import 'package:xindong/manager/xindong_user_controller.dart';
import 'package:xindong/utils/xindong_calender_util.dart';

// 每日重置
class XinDongDailyResetSingleton {
  // 启动应用时间戳（int）
  final String dailyResetTimestamp = "sp_dailyResetTimestamp";

  // 今日缘份
  bool canShowTodayFate = false;

  // 实例化
  void setup() async {
    if (XinDongUserController.to.isUserCompleted == false) {
      return;
    }
    int serverTimestamp = DateTime.now().millisecondsSinceEpoch;
    int saveTimestamp = XinDongStorage.instance.getInt(dailyResetTimestamp) ?? 0;
    if (saveTimestamp == 0) {
      XinDongStorage.instance.saveInt(dailyResetTimestamp, serverTimestamp);
      _reset();
    } else {
      bool isToday = XinDongCalendarUtil.isSameDay(
        DateTime.fromMillisecondsSinceEpoch(saveTimestamp),
        DateTime.fromMillisecondsSinceEpoch(serverTimestamp),
      );
      if (!isToday) {
        XinDongStorage.instance.saveInt(dailyResetTimestamp, serverTimestamp);
        _reset();
      }
    }
  }

  // 重置
  Future<void> _reset() async {
    mDebugPrint("每日重置");
    canShowTodayFate = true;
    XinDongUserController.to.updateSig();
  }

  /// ======== 单例
  // 工厂方法构造函数
  factory XinDongDailyResetSingleton() => _getInstance();

  // instance的getter方法，singletonManager.instance获取对象
  static XinDongDailyResetSingleton get instance => _getInstance();

  // 静态变量_instance，存储唯一对象
  static XinDongDailyResetSingleton? _instance;

  // 获取对象
  static XinDongDailyResetSingleton _getInstance() {
    _instance ??= XinDongDailyResetSingleton._internal();
    return _instance!;
  }

  // 私有的自定义命名式构造方法，通过它实现一个类;
  // 子类不能继承internal
  // 不是关键字，可定义其他名字
  XinDongDailyResetSingleton._internal() {
    //初始化(设置一些默认的)...
  }
}
